﻿//************************************************************************************************
// Copyright © 2003-2012 Steven M. Cohn. All Rights Reserved.
//
// Facility:	Microsoft Development Environment 2012  Version 11.0.50727.1
// Environment:	Microsoft .NET Framework 4.5            Version v4.0.30319
//
// Description: Defines the custom sorting algorithm for the listCookies listview.
//
// Revision History:
// -Who--------------- -When---------- -What------------------------------------------------------
// Steven M. Cohn		18-Oct-2003		New
// Steven M. Cohn		12-Oct-2004		VS.NET 2005, .NET 2.0
// Steven M. Cohn		20-Nov-2012		Refresh! VS2010 .NET 4.5 64-bit
//************************************************************************************************

namespace CookieChipper
{
	using System;
	using System.Collections;
	using System.Windows.Forms;


	/// <summary>
	/// Item comparer used to sort the cookie view.
	/// </summary>

	internal class ListViewItemComparer : IComparer
	{
		private int column;


		/// <summary>
		/// Initialize a new comparer
		/// </summary>
		/// <param name="column"></param>

		public ListViewItemComparer (int column)
		{
			this.column = column;
		}


		/// <summary>
		/// 
		/// </summary>

		public int Column
		{
			get { return column; }
			set { column = value; }
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="x"></param>
		/// <param name="y"></param>
		/// <returns></returns>

		public int Compare (object x, object y)
		{
			ListView view = ((ListViewItem)x).ListView;
			Type type = view.Columns[column].Tag as Type;

			ListViewItem.ListViewSubItem subx = ((ListViewItem)x).SubItems[column];
			ListViewItem.ListViewSubItem suby = ((ListViewItem)y).SubItems[column];

			if (view.Sorting == SortOrder.Ascending)
			{
				if (type.Equals(typeof(String)))
				{
					return String.Compare(subx.Text, suby.Text);
				}
				else if (type.Equals(typeof(Int32)))
				{
					int a = (int)subx.Tag;
					int b = (int)suby.Tag;
					return a < b ? -1 : (a > b ? 1 : 0);
				}
				else
				{
					return DateTime.Compare((DateTime)subx.Tag, (DateTime)suby.Tag);
				}
			}
			else
			{
				if (type.Equals(typeof(String)))
				{
					return String.Compare(suby.Text, subx.Text);
				}
				else if (type.Equals(typeof(Int32)))
				{
					int a = (int)subx.Tag;
					int b = (int)suby.Tag;
					return b < a ? -1 : (b > a ? 1 : 0);
				}
				else
				{
					return DateTime.Compare((DateTime)suby.Tag, (DateTime)subx.Tag);
				}
			}
		}
	}
}